package com.wangxaing.gateway.config;


import com.wangxaing.gateway.dao.AuthDao;
import com.wangxaing.gateway.dao.RoleAuthDao;
import com.wangxaing.gateway.dao.RoleDao;
import com.wangxaing.gateway.entity.AuthEntity;
import com.wangxaing.gateway.entity.RoleEntity;

import com.wangxaing.gateway.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
@RestController

public class AccessFilter implements GlobalFilter, Ordered {
    @Autowired
    UnInterceptList unInterceptList;
    @Autowired
    private RoleAuthDao roleAuthDao;
    @Autowired
    private AuthDao authDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RedisUtils redisUtils;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /**
         * uniapp
         */


        /**
         * 白名单login
         * 白名单，管理系统白名单有验证码，登录接口
         */
        String urlapi = exchange.getRequest().getURI().getPath();
//        System.out.println("请求路径"+urlapi);
        String passUrl = unInterceptList.pass();

        String login = "/api/sys/login";
        String lognOut = "/api/sys/loginOut";


        if(login.equals(urlapi)|lognOut.equals(urlapi)){
            System.out.println("登录或退出");
            Map<String, Object> hashMap = new HashMap<>();
            exchange.getRequest().getHeaders().forEach((key,value)->{
//                System.out.println(key+": "+value);
                hashMap.put(key,value);
            });
            redisUtils.hmset("loginOrloginOut",hashMap,60);
//            redisUtils.set("loginOrloginOut",exchange.getRequest().getHeaders().toSingleValueMap(),12000);
        }







        if (passUrl.contains(urlapi)){
//            System.out.println("白名单"+urlapi);
            return chain.filter(exchange);
        }


        /**
         * =============================================
         *
         *
         * 网关权限重构
         * 舍弃jwt方式，使用权限表进行校验
         * 这次为项目整体重构，项目重点为业务而不是安全
         *
         *
         * =============================================
         */
        /**
         * 网关权限重构
         */

        //通过角色id查询，权限id,关系表role_auth,角色信息存储到请求头
        String roleidlist = exchange.getRequest().getHeaders().get("roleId").get(0);
//        System.out.println(""+exchange.getRequest().getHeaders().get("roleId"));
//        System.out.println("权限id="+roleidlist);
        String nullStr = "null";
//        if (roleidlist==null|nullStr.equals(roleidlist)){
////            System.out.println("没有权限，权限id");
//            ServerHttpResponse response = exchange.getResponse();
//            response.getHeaders()
//                    .add("Content-Type","application/json;charset");
//            String msg = "{\"msg\":\""+"权限超时，请重新登录"+"\"}";
//            DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes());
//            return response.writeWith(Mono.just(buffer));
//        }
            int roleId = Integer.valueOf(roleidlist);
            List<Integer> authIdList = roleAuthDao.getAuthIdListByRoleId(roleId);

            ArrayList<String> authList = new ArrayList<>();
            //查询关系表
            authIdList.forEach((authItem)->{
                AuthEntity authEntity = authDao.selectById(authItem);
                if (authEntity!=null){
                    authList.add("/api/"+authEntity.getAuth());
                }
            });



            //权限校验
            for (int i = 0; i < authList.size(); i++) {
//            System.out.println("权限"+authList.get(i));
                if (authList.get(i)==urlapi|urlapi.equals(authList.get(i))){
                    return chain.filter(exchange);
                }
            }
//        System.out.println("没有权限");
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders()
                    .add("Content-Type","application/json;charset");
            String msg = "{\"msg\":\""+"没有权限"+"\"}";

            DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes());
            return response.writeWith(Mono.just(buffer));



    }

    @Override
    public int getOrder() {
        return 0;
    }
}
